package io.task.cc.network.maintain;

import io.task.cc.network.ChannelContext;
import io.task.cc.network.utils.lock.LockedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 一对一  (bsid <--> ChannelContext)<br>
 * Bs: business，业务id和ChannelContext绑定<br>
 * 需求见：https://gitee.com/tywo45/t-io/issues/IK30Q
 */
public class BsIds {
    private static final Logger log = LoggerFactory.getLogger(BsIds.class);

    /**
     * key: 业务id
     * value: ChannelContext
     */
    private final LockedMap<String, ChannelContext> map = new LockedMap<>(new HashMap<String, ChannelContext>());


    public void bind(String bsId, ChannelContext channelContext) {

        try {
            //先解绑，否则如果业务层绑定两个不同的bsid，就会导致资源释放不掉
            unbind(channelContext);

            if (bsId == null) {
                return;
            }
            channelContext.setBsId(bsId);
            map.put(bsId, channelContext);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }


    public ChannelContext find(String bsId) {


        if (bsId == null) {
            return null;
        }

        return map.get(bsId);
    }


    public void unbind(ChannelContext channelContext) {

        String bsId = channelContext.getBsId();
        if (bsId == null) {
            return;
        }
        try {
            map.remove(bsId);
            channelContext.setBsId(null);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}
